<script lang="ts" setup>
// 父组件传递数据
const props = defineProps({
  limitCountFile: {
    type: Number,
    default: 1,
  },
});
// 定义暴露事件名
const emit = defineEmits(['handleFileSuccess']);

/**
 * 上传文件配置：
 * uploadRef 上传组件ref
 * fileConfig: {
    fileList: [], // 上传文件列表
  }
 * handelExceed 上传的文件个数超出设定时触发的函数
 * handelChange
 * handelRemove
 * handleClear 清空已上传的文件列表
 */
const uploadRef = ref(null);
const fileConfig = reactive({
  noneBtnImg: false,
  fileList: [],
});
const handelExceed = () => {
  ElMessage.warning({ message: `最多只能上传${props.limitCountFile}个文件` });
};
const handelRemove = (file, fileList) => {
  emit('handleFileSuccess', '');
};
const handleClear = () => {
  uploadRef.value.clearFiles();
};
const handelChange = (file, fileList) => {
  console.log(file);
  let arr = ['application/json'];
  let isFormat = arr.includes(file.raw.type);
  if (!isFormat) {
    ElMessage.warning({
      message: `仅支持.json 格式文件!`,
    });
    handleClear();
    return;
  }
  emit('handleFileSuccess', file);
};
</script>

<template>
  <div class="upload_file">
    <el-upload
      class="upload-demo"
      :auto-upload="false"
      :limit="limitCountFile"
      :on-exceed="handelExceed"
      :on-change="handelChange"
      :on-remove="handelRemove"
      :file-list="fileList"
      ref="uploadRef"
    >
      <el-button type="primary">
        <el-icon style="margin-right: 3px"><Plus /></el-icon>
        上传文件
      </el-button>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.upload_file {
  width: 100%;
  height: 40px !important;
  ::v-deep .el-upload-list {
    margin: 0;
  }
}
</style>
